package com.prdiot.poetry.service;

import com.prdiot.poetry.dao.*;
import com.prdiot.poetry.domains.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TagsService {

    @Autowired
    TagsRepository tagsRepository;

    //key tag_name val:tag_id
    private static final Map<String, String> tagsMap = new HashMap<>();
    private static volatile boolean tagsMapInit = false;

    //获取tag 缓存map
    public Map<String, String> getTagsMap(){
        //经典单例 双重检测 确保线程安全
        if(!tagsMapInit) {
            synchronized (TagsService.class) {
                if (!tagsMapInit) {
                    initTags();
                    tagsMapInit = true;
                }
            }
        }
        return tagsMap;
    }

    private void initTags(){
        List<Tags> tags = tagsRepository.findAll();
        tagsMap.clear();
        for (Tags tag:tags) {
            tagsMap.put(tag.getTagName().trim(),tag.getTagId());
        }
    }

    public List<Tags> getTagsOrderByPoemCount(){
        Sort sort = new Sort(Sort.Direction.DESC, "poemCount");
        return tagsRepository.findAll(sort);
    }

    public List<Tags> getTagsOrderByPoemCount(int tagCount){
        Sort sort = new Sort(Sort.Direction.DESC, "poemCount");
        return tagsRepository.findAll(sort).subList(0,tagCount);
    }

}
